<?php

class IndexController extends Site_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        Zend_Loader::loadClass('auth','library');
        Zend_Loader::loadClass('datetools','library');
                
        $obj = new Ead_Model_DbTable_Minibanner();
        $this->view->minibaner = $obj->fetchAll($obj->select()->where('BAN_STA = 1')->order('BAN_ORD ASC'));
        
       /*
        Zend_Loader::loadClass('facebook','library');

        $facebook = new Facebook(array(
        'appId'  => '688243397900389',
        'secret' => 'd4f5387e75619c4ad2de421119720c20',
      ));
        
        $user = $facebook->getUser();
        if ($user) {
            try {
              // Proceed knowing you have a logged in user who's authenticated.
              $user_profile = $facebook->api('/me');
            } catch (FacebookApiException $e) {
              error_log($e);
              $user = null;
            }
          }

          // Login or logout url will be needed depending on current user state.
          if ($user) {
            $logoutUrl = $facebook->getLogoutUrl();
          } else {
            $statusUrl = $facebook->getLoginStatusUrl();
            $loginUrl = $facebook->getLoginUrl();
          }
echo $loginUrl;
          // This call will always work since we are fetching public data.
          $naitik = $facebook->api('/naitik');
        */
        
        $appId = $this->fb_appId; //'142491082620110'; // Senha da app 
        $appSecret = $this->fb_appSecret; //'6ab3c1601ee76e6a0b11252261a3b8d4'; // Url informada no campo "Site URL" 
        $redirectUri = urlencode($this->fb_redirectUri); //urlencode('http://neneco.com.br/site/'); 

        $code = @$_GET['code'];   

        $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $appId . "&redirect_uri=" . $redirectUri . "&client_secret=" . $appSecret . "&code=" . $code;   
        $response = @file_get_contents($token_url);
        if($response){
            $params = null; 
            parse_str($response, $params);   
            if(isset($params['access_token']) && $params['access_token']){ 
                $graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];  
                $user = json_decode(file_get_contents($graph_url));  
                //print_r($user);
                //exit();
                // verificar se usuário existe

                $obj = new Ead_Model_DbTable_Usuarios();
                $row = $obj->fetchRow('USU_EMAIL like "'.$user->email.'" or USU_LOGIN = "'.$user->email.'"');
                
                if(isset($row->USU_ID)){
                    //echo $row->USU_LOGIN.' - '.$row->USU_EMAIL;
                    $login = $row->USU_LOGIN;
                    $senha = '';
                }else {
                    
                    $login = $user->username;
                    $senha = date('YmdHis');
                    $data = array(
                           //'USU_ID'        => $form->getValue('USU_ID'),
                           'USU_EMAIL' => $user->email,
                           'USU_LOGIN' => $login,
                           'USU_CPF' => '',
                           'USU_NOME' => $user->name,
                           'PER_ID' => 5, // permissão alunos
                           'USU_DTCADASTRO' => date('Y-m-d'),
                           'USU_TPO' => 2, // 2 = alunos
                           'USU_SENHA' => sha1($senha),
                           'USU_CADSTA' => 0,
                           'USU_STA' => 1,
                           'USU_CIDADE' => $user->location->name,
                           'USU_DTNASC' => Datetools::mda_amd($user->birthday),
                       );

                       $obj = new Ead_Model_DbTable_Usuarios();

                       $ok = $obj->insert($data);
                       
                       if($ok){
                    
                            $arr['email'] = $user->email;
                            $arr['nome'] = $user->name;
                            $arr['login'] = $login;
                            $arr['senha'] = $senha;

                            Zend_Loader::loadClass('envioemail','library');
                            envioemail::Cadastro($arr);
                        }
               }

               $dbAdapter = Zend_Db_Table::getDefaultAdapter();
               //Inicia o adaptador Zend_Auth para banco de dados
               $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
               $authAdapter->setTableName('USUARIOS')
                       ->setIdentityColumn('USU_LOGIN')
                       ->setCredentialColumn('USU_LOGIN');// USU_SENHA
                       //->setCredentialTreatment('SHA1(?)');

               //Define os dados para processar o login
               $authAdapter->setIdentity($login)
                       ->setCredential($login);

               //Efetua o login
               $auth = Zend_Auth::getInstance();
               $result = $auth->authenticate($authAdapter);
               
               $info = $authAdapter->getResultRowObject(null, 'USU_LOGIN');
               $storage = $auth->getStorage();
               $storage->write($info);
               
               // valida status do usuário
                Zend_Loader::loadClass('usuario','library');
                if(!Usuario::ValidarStaUsu($storage->read()->USU_ID)){
                    //Dados inválidos
                    $this->_helper->FlashMessenger('Usuário ou senha inválidos!');
                    return $this->_helper->redirector('index', 'index', array());
                }

                Usuario::setIdSessaoUsu($storage->read()->USU_ID, session_id());
               
                auth::montaSessao($auth,$authAdapter);
               
            }

        }

        
    }


}

